/**
 * 
 */
package com.vision.core.sv.db.mgr;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 * Provides very basic data access operations (CRUD).
 * 
 * @author Mark
 *
 */
public abstract class DataManager<T> implements IDataManager<T> {
	
	private HibernateTemplate template;
	
	public SessionFactory getSessionFactory() {
		return template.getSessionFactory();
	}
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.template = new HibernateTemplate(sessionFactory);
		
		// We ensure that a new session is created every time an operation is
		// made, so that objects are always in a detached state. 
		this.template.setAlwaysUseNewSession(true);
	}
	
	public HibernateTemplate getTemplate() {
		return template;
	}
	
	public Session openSession() {
		return getSessionFactory().openSession();
	}

	@Override
	public T create(T object) {
		template.save(object);
		return object;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getAll() {
		return template.find("from " + getManagedClass().getName());
	}

	@Override
	public T getById(Serializable id) {
		return template.get(getManagedClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> getByIds(String idColumn, List<?> ids) {
		ISimpleCriteria crit = SimpleCriteria.forClass(getManagedClass());
		crit.in(idColumn, ids);
		
		return template.findByCriteria(crit.getDetached());
	}

	@Override
	public T update(T object) {
		template.update(object);
		return object;
	}

	@Override
	public T delete(T object) {
		template.delete(object);
		return object;
	}
	
}
